<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true">
				<el-form-item>
					<el-input v-model="keyword" placeholder="关键字"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="warning" v-on:click="keywordQuery">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" v-perm="'article:add'"  @click="handleAdd">新增</el-button>
				</el-form-item>
			</el-form>
		</el-col>

		<!--列表v-loading="listLoading"-->
		<el-table :data="tableDatas" v-loading="listLoading" @selection-change="handleSelectionChange"
			highlight-current-row style="width: 100%;">
			<!--多选框-->
			<el-table-column type="selection" width="55">
			</el-table-column>
			<el-table-column type="index" width="70" label="序号">
			</el-table-column>
			<el-table-column prop="articleName" label="文章名称" width="120">
			</el-table-column>
			<el-table-column prop="articleTag" label="文章标签" width="120">
			</el-table-column>
			<el-table-column label="文章封面" width="120">
				<template slot-scope="scope">
					<img :src="scope.row.articlePic" width="80px" alt="加载失败"></img>
				</template>
			</el-table-column>
			<el-table-column prop="at.typeName" label="文章类型" width="120">
			</el-table-column>
			<el-table-column prop="articleState" label="文章状态" width="120">
				<template scope="scope">
					<span v-if="scope.row.articleState == 2" style="color: red;">弃用</span>
					<span v-if="scope.row.articleState == 1" style="color: green;">发布</span>
					<span v-if="scope.row.articleState == 0" style="color: blue;">草稿</span>
				</template>
			</el-table-column>
			<el-table-column prop="topState" label="是否置顶" width="120">
				<template scope="scope">
					<span v-if="scope.row.topState == 1" style="color: green;">置顶</span>
					<span v-if="scope.row.topState == 0" style="color: red;">不置顶</span>
				</template>
			</el-table-column>
			<el-table-column prop="user.realName" label="发布人" width="120">
			</el-table-column>
			<el-table-column prop="createTime" label="添加时间" width="150">
			</el-table-column>
			<el-table-column prop="updateTime" label="修改时间" width="200">
			</el-table-column>
			<el-table-column prop="articleReadCount" label="文章阅读量" width="120">
			</el-table-column>
			<el-table-column prop="articleStarNum" label="文章点赞数" width="120">
			</el-table-column>
			<el-table-column prop="articleCommentNum" label="文章评论数" width="120">
			</el-table-column>
			<el-table-column prop="articleRemark" label="文章简介" width="120" show-overflow-tooltip=true>
			</el-table-column>
			<el-table-column prop="articleContent" label="文章内容" width="120" show-overflow-tooltip=true>
			</el-table-column>
			<el-table-column label="操作">
				<template scope="scope">
					<el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
					<el-button type="danger"  size="small" @click="handleDel(scope.row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>
		<!--工具条-->
		<el-col :span="24" class="toolbar">
			<el-button type="danger" :disabled="this.sels.length === 0" @click="handlePatchDel">批量删除</el-button>
			<el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
				:current-page="currentPage" :page-sizes="[5, 10, 15]" :page-size="pageSize"
				layout="total, sizes, prev, pager, next, jumper" :total="totals" style="float:right;">
			</el-pagination>
		</el-col>

		<!--添加或修改界面-->
		<el-dialog :title="title" :visible.sync="saveFormVisible" :close-on-click-modal="false">
			<el-form :model="saveForm" label-width="80px" :rules="saveFormRules" ref="saveForm">
				<el-form-item label="文章名称" prop="articleName">
					<el-input v-model="saveForm.articleName" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="文章封面" prop="articlePic">
<!--					<el-input v-model="saveForm.articlePic" auto-complete="off"></el-input>-->
<!--          action:上传接口地址（自己应用里面的）
              on-preview：预览的事件
              on-remove：移除当前图片的时候的处理事件
              on-success:文件上传成功后的处理函数
              file-list：文件列表

              :auto-upload="false" //阻止选择文件时自动上传
              :http-request="customUpload" //自定义上传的实现
              ref="upload"//给这个组件取一个名字 一会要用
-->
          <el-upload
              class="upload-demo"
              action="http://localhost:8080/minio"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :on-success="handleSuccess"
              :file-list="fileList"
              list-type="picture"

              :auto-upload="false"
              :http-request="customUpload"
              ref="upload"
              >
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
				</el-form-item>
				<el-form-item label="文章标签" prop="articleTag">
					<el-input v-model="saveForm.articleTag" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="文章类型">
					<!-- <el-input v-model="saveForm.parentId" auto-complete="off"></el-input> -->
					<el-cascader :options="options"
						:props="{ checkStrictly: true, label: 'typeName', value: 'id', emitPath: false }" clearable
						v-model="saveForm.articleType"></el-cascader>
				</el-form-item>
				<el-form-item label="文章状态">
					<!-- <el-input v-model="saveForm.status" auto-complete="off"></el-input> -->
					<el-radio v-model="saveForm.articleState" :label="0">草稿</el-radio>
					<el-radio v-model="saveForm.articleState" :label="1">发布</el-radio>
					<el-radio v-model="saveForm.articleState" :label="2">弃用</el-radio>
				</el-form-item>
				<el-form-item label="是否置顶">
					<!-- <el-input v-model="saveForm.status" auto-complete="off"></el-input> -->
					<el-radio v-model="saveForm.topState" :label="0">不置顶</el-radio>
					<el-radio v-model="saveForm.topState" :label="1">置顶</el-radio>
				</el-form-item>
				<el-form-item label="文章简介" prop="articleRemark">
					<el-input v-model="saveForm.articleRemark" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="文章内容" prop="articleContent">
<!--					<el-input v-model="saveForm.articleContent" auto-complete="off"></el-input>-->
          <quill-editor v-model="saveForm.articleContent"
                        :options="quillOption"
                        @ready="onEditorReady($event)">
          </quill-editor>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="saveFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="saveSubmit">提交</el-button>
			</div>
		</el-dialog>
	</section>
</template>

<script>
import { status } from 'nprogress';
//引入Vue的ueditor的资源
import { quillEditor } from "vue-quill-editor"; //调用编辑器
import 'quill/dist/quill.core.css';
import 'quill/dist/quill.snow.css';
import 'quill/dist/quill.bubble.css';
import quillConfig from '../../common/js/quill-config'
import el from "element-ui/src/locale/lang/el";
// 工具栏配置
const toolbarOptions = [
  ["bold", "italic", "underline", "strike"], // 加粗 斜体 下划线 删除线 -----['bold', 'italic', 'underline', 'strike']
  ["blockquote", "code-block"], // 引用  代码块-----['blockquote', 'code-block']
  [{header: 1}, {header: 2}], // 1、2 级标题-----[{ header: 1 }, { header: 2 }]
  [{list: "ordered"}, {list: "bullet"}], // 有序、无序列表-----[{ list: 'ordered' }, { list: 'bullet' }]
  [{script: "sub"}, {script: "super"}], // 上标/下标-----[{ script: 'sub' }, { script: 'super' }]
  [{indent: "-1"}, {indent: "+1"}], // 缩进-----[{ indent: '-1' }, { indent: '+1' }]
  [{direction: "rtl"}], // 文本方向-----[{'direction': 'rtl'}]
  [{size: ["small", false, "large", "huge"]}], // 字体大小-----[{ size: ['small', false, 'large', 'huge'] }]
  [{header: [1, 2, 3, 4, 5, 6, false]}], // 标题-----[{ header: [1, 2, 3, 4, 5, 6, false] }]
  [{color: []}, {background: []}], // 字体颜色、字体背景颜色-----[{ color: [] }, { background: [] }]
  [{font: []}], // 字体种类-----[{ font: [] }]
  [{align: []}], // 对齐方式-----[{ align: [] }]
  ["clean"], // 清除文本格式-----['clean']
  ["image", "link"] // 链接、图片、视频-----['link', 'image', 'video']
];

export default {
  components: {
    quillEditor
  },
	data() {
		return {
      quillOption: quillConfig,
      fileList:[],
      //富文本编辑器配置
      editorOption: {
        modules: {
          //工具栏定义的
          toolbar: toolbarOptions
        },
        //主题
        theme: "snow",
        placeholder: "请开始书写您的博客内容..."
      },
			//1.分页查询相关数据
			totals: 0,//总记录条数
			currentPage: 1,//当前页,要传递到后台的
			pageSize: 5, //每页显示多少条
			tableDatas: [], //当前页数据
			listLoading: false,
			options: [],// 级联选择器数据

			//2.高级查询相关数据
			keyword: '',

			//3.删除相关数据

			//4.批量删除相关数据
			sels: [], //存储多选记录

			//5.添加和修改相关数据
			title: '',
			saveFormVisible: false,
			saveForm: {
				id: null,
				articlePic: '',
				articleName: '',
				articleTag: '',
				articleType: null,
				articleState: null,
				topState: null,
				articleRemark: '',
				articleContent: ''
			},

			//6.添加和修改校验规则-表单项校验
			saveFormRules: {
				articleName: [
					{ required: true, message: '请输入文章名称', trigger: 'blur' }
				],
				articleRemark: [
					{ required: true, message: '请输入文章简介', trigger: 'blur' }
				],
				articleContent: [
					{ required: true, message: '请输入文章内容', trigger: 'blur' }
				],
			},

		}
	},
	methods: {

    /*
    文件上传成功处理函数
    使用返回回来的文件名 拼接访问图片url
    */
    handleSuccess(response, file, fileList){
      console.log(response);
      this.saveForm.articlePic = "http://localhost:9000/testbucket/" + response.data
    },
    handleRemove(file, fileList) {
      console.log(file);
      let fileName = null;
      if (file.response){//删除新上传的
        fileName = file.response.data;
      }else {//删除回显的
        let urlStr = file.url;//http://localhost:9000/testbucket/1754884121548.jpg
        fileName = urlStr.substring(urlStr.lastIndexOf("/") + 1)
      }
      this.$http.delete("/minio/" + fileName).then(res=>{
        if (res.data.success){
          this.saveForm.articlePic = null;
          this.$message.success("删除成功")
        }else {
          this.$message.error("删除失败")
        }
      }).catch(res=>{
        this.$message.error("网络异常")
      })
    },
    handlePreview(file) {
      console.log(file);
    },
    onEditorReady(editor) {
      //当富文本编辑框初始化好执行
      console.log('富文本编辑框初始化---------完成');
    },
		//1.分页查询相关方法
		//1.1.获取列表数据
		getTableData() {
			let params = {
				currentPage: this.currentPage,
				pageSize: this.pageSize,
				keyword: this.keyword
			};
			this.listLoading = true;
			this.$http.post('/article', params).then((res) => {
				// console.log(res);
				this.tableDatas = res.data.list;
				this.totals = res.data.total;
				this.listLoading = false;
			}).catch((res) => {
				this.$message.error('服务器忙!');
			})

		},
		//1.2.选择第几页时触发
		handleCurrentChange(currentPage) {
			this.currentPage = currentPage;
			this.getTableData();
		},
		//1.3.选择每页显示记录条数时触发
		handleSizeChange(pageSize) {
			this.pageSize = pageSize;
			this.getTableData();
		},

		//2.高级查询相关方法
		keywordQuery() {
			this.currentPage = 1;
			this.getTableData();
		},

		//3.删除相关方法
		handleDel(row) {
			// console.log(row.id);
			this.$confirm('此操作将永久删除该类型 [' + row.userName + '] , 是否继续?', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(() => {
				this.$http.delete('/article/' + row.id).then((res) => {
					this.$message.success('删除成功!');
					this.getTableData();
				}).catch((res) => {
					this.$message.error('服务器忙!');
				})
			}).catch(() => {
				this.$message({
					type: 'info',
					message: '已取消删除'
				});
			});

		},


		//4.批量删除相关方法
		//4.1.选项改变时触发
		handleSelectionChange(val) {
			// console.log(val);
			this.sels = val.map(row => row.id);
			// console.log(this.sels);
		},
		//4.2.批量删除
		handlePatchDel() {
			this.$confirm('此操作将永久删除选中类型, 是否继续?', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(() => {
				this.$http.patch('/article', this.sels).then((res) => {
					this.$message.success('删除成功!');
					this.currentPage = 1;
					this.getTableData();
				}).catch((res) => {
					this.$message.error('服务器忙!');
				})
			}).catch(() => {
				this.$message({
					type: 'info',
					message: '已取消删除'
				});
			});
		},

		getTypeTree(id) {
			this.$http.get('/articleType/treeType/' + id).then((res) => {
				this.options = res.data.data;
			}).catch((res) => {
				this.$message.error('服务器忙!');
			})
		},

		//5.添加和修改相关方法
		//5.1.点击添加弹出对话框
		handleAdd() {
			this.title = '添加';
			this.saveForm = {
				articleState: 0,
				topState: 0
			};
			this.getTypeTree(-1);
			this.$nextTick(() => {
				this.$refs.saveForm.clearValidate(); // 可选：只清除校验提示，不重置值
			});
      this.fileList = [];
			this.saveFormVisible = true;
		},
		//5.2.点击修改弹出对话框
		handleEdit(row) {
			this.title = '编辑';
			this.getTypeTree(-1);
			this.$nextTick(() => {
				this.$refs.saveForm.clearValidate(); // 可选：只清除校验提示，不重置值
			});
			this.saveForm = Object.assign({}, row);
      //要让封面图片能显示出来 fileList必须要有值
      this.fileList = [];
      this.fileList.push({url:this.saveForm.articlePic})
			this.saveFormVisible = true;
		},
    async customUpload(options) {
      //创建一个表单对象
      const formData = new FormData();
      if (options) {
        // 添加文件
        formData.append('file', options.file);
      }

      // 添加其他表单字段
      let param = {}
      if (this.saveForm.id){//如果是编辑 处理一下
        param.id = this.saveForm.id;
        param.articlePic = this.saveForm.articlePic;
        param.articleName = this.saveForm.articleName;
        param.articleTag = this.saveForm.articleTag;
        param.articleType = this.saveForm.articleType;
        param.articleState = this.saveForm.articleState;
        param.topState = this.saveForm.topState;
        param.articleRemark = this.saveForm.articleRemark;
        param.articleContent = this.saveForm.articleContent;
      }else {
        param = this.saveForm
      }

      Object.keys(param).forEach(key => {
        if (key !== 'file') {
          formData.append(key, param[key]);
        }
      });
      try {
        const res =await this.$http.put('/article', formData, {
          headers: { 'Content-Type': 'multipart/form-data' }
        });
        // 处理成功逻辑
        if (res.data.success) {
          this.$message.success('保存成功!');
          if (this.saveForm.id == null) {
            this.totals++;
            this.currentPage = Math.ceil(this.totals / this.pageSize);
          }
          this.saveFormVisible = false;
          this.getTableData();
        } else {
          this.$message.error(res.data.message);
        }
      } catch (err) {
        // 处理错误
        this.$message.error("网络异常");
      }
    },
		//5.3.提交表单数据操作数据库
		saveSubmit() {
			this.$refs.saveForm.validate(valid => {
				if (valid) {
          const file = this.$refs.upload.uploadFiles[0];
          // console.log("file:")
          // console.log(file)
          if (file && file.raw) {//刚刚上传的
            // 手动触发上传（会调用http-request）
            this.$refs.upload.submit();
          }else {//如果用户没有选择文件
            // 即使调用this.$refs.upload.submit()这个方法
            //customeUpload方法也不会执行
            this.customUpload()
          }
				} else {
					//表单验证失败
					this.$message.error('表单校验未通过,请输入必填项!');
					return false;
				}
			})
		}

	},
	mounted() {
		this.getTableData();
	}
}

</script>

<style scoped></style>
